package com.ruoyi.biz.attchment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.biz.attchment.domain.BizAttachment;
import com.ruoyi.biz.attchment.mapper.BizAttachmentMapper;
import com.ruoyi.biz.attchment.service.IBizAttachmentService;
import com.ruoyi.common.enums.AttachementType;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 附件Service业务层处理
 *
 * @author Fei.Cong
 * @date 2023-03-28
 */
@Slf4j
@Service
public class BizAttachmentServiceImpl extends ServiceImpl<BizAttachmentMapper, BizAttachment> implements IBizAttachmentService {

    @Autowired
    private BizAttachmentMapper bizAttachmentMapper;

    /**
     * 分页查询附件
     *
     * @param page
     * @param bizAttachment 附件
     */
    @Override
    public IPage<BizAttachment> pageList(BizAttachment bizAttachment, IPage<BizAttachment> page) {
        return bizAttachmentMapper.selectPageList(page, bizAttachment);
    }

    @Override
    public void batchAdd(List<BizAttachment> bizAttachmentList, Long applyId, String createBy, AttachementType type) {

        if (CollectionUtil.isNotEmpty(bizAttachmentList)) {
            this.remove(new LambdaQueryWrapper<BizAttachment>().eq(BizAttachment::getApplyId, applyId)
                    .eq(BizAttachment::getAttachmentType, type.getCode()));
            List<BizAttachment> attachments = Lists.newArrayList();
            for (BizAttachment bizAttachment : bizAttachmentList) {
                if (StrUtil.isBlank(bizAttachment.getFilePath())) {
                    throw new ServiceException(String.format("必须上传附件资料,%s", bizAttachment.getFileName()));
                }
                String[] splitFile = bizAttachment.getFilePath().split(",");
                for (String filePath : splitFile) {
                    BizAttachment attachment = new BizAttachment();
                    attachment.setId(null);
                    attachment.setFilePath(filePath);
                    attachment.setFileName(bizAttachment.getFileName());
                    attachment.setAttachmentType(type.getCode());
                    attachment.setApplyId(applyId);
                    attachment.setCreateBy(createBy);
                    attachment.setRemark(bizAttachment.getRemark());
                    attachments.add(attachment);
                }
            }
            boolean b = this.saveBatch(attachments);
            log.info("附件类型:{},申请id:{},saveBatch:{}", type.getDesc(), applyId, b);
        }

    }

}
